package com.yamaha.bikedesalon;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.yamaha.bikedesalon.util.API;
import com.yamaha.bikedesalon.util.SCStaticFunc;

public class PostPartFragment extends AMyActivity
		implements
			OnItemClickListener,
			TextWatcher,
			TextView.OnEditorActionListener {

	private final String TAG = this.getClass().getSimpleName();
	private final List<JSONObject> list = new ArrayList<JSONObject>();
	private final List<JSONObject> filterdList = new ArrayList<JSONObject>();
	private final MyAdapter adapter = new MyAdapter();
	private EditText searchField;
	public PostPartFragment() {
		super(MenuType.POST_PART);
	}

	@Override
	protected List<EditText> getEditTexts() {
		final ArrayList<EditText> list = new ArrayList<EditText>();

		return list;
	}

	@Override
	public void onMyClick(View v) {
		switch (v.getId()) {
			case R.id.post_part_add_button : {
				doNew();
			}
				break;
		}
	}

	private void doNew() {
		final Intent intent = new Intent(this, AddEditFormFragment.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		startActivity(intent);
	}

	@Override
	protected int getLayoutId() {
		return R.layout.post_part_page;
	}

	@Override
	protected void onMyCreated(Bundle savedInstanceState) {
		final ListView listView = (ListView) this.findViewById(R.id.post_part_list_view);
		listView.setAdapter(this.adapter);
		listView.setOnItemClickListener(this);

		final boolean pauseOnScroll = true; // or true
		final boolean pauseOnFling = true; // or false
		final PauseOnScrollListener listener = new PauseOnScrollListener(this.imageLoader, pauseOnScroll, pauseOnFling);
		listView.setOnScrollListener(listener);

		final ImageButton newButton = (ImageButton) findViewById(R.id.post_part_add_button);
		newButton.setOnClickListener(this);

		searchField = (EditText) findViewById(R.id.editText1);
		searchField.addTextChangedListener(this);
		searchField.setOnEditorActionListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();

		getData(true);
	}

	private void getData(final boolean isLoading) {

		adapter.setLoading(isLoading);
		adapter.notifyDataSetChanged();

		final AsyncHttpClient client = new AsyncHttpClient();
		final RequestParams params = new RequestParams();
		params.put("filter_user_id", SCStaticFunc.getUserId(this));
		LogUtil.v(TAG, "Params : " + params.toString());
		client.post(API.POST_PART, params, new MyAsyncHttpResponseHandler(API.POST_PART, this) {

			@Override
			protected void onAsyncSuccess(final Object res)
					throws JSONException {

				list.clear();
				filterdList.clear();
				final JSONArray items = (JSONArray) res;
				for (int i = 0; i < items.length(); i++) {
					list.add(items.getJSONObject(i));
				}

				filterdList.addAll(list);

				adapter.setLoading(false);
				adapter.notifyDataSetChanged();
			}
		});
	}

	private class MyAdapter extends BaseAdapter
			implements
				View.OnClickListener,
				View.OnLongClickListener,
				Filterable {

		private boolean isLoading;

		public void setLoading(final boolean isLoading) {
			this.isLoading = isLoading;
		}

		@Override
		public int getCount() {
			if (this.isLoading) {
				return 1;
			}
			return filterdList.size();
		}

		@Override
		public Object getItem(int position) {
			if (this.isLoading) {
				return null;
			}
			return filterdList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (this.isLoading) {
				convertView = inflater.inflate(R.layout.loading_item, parent, false);
				convertView.setId(0x0123);
				return convertView;
			}

			if ((convertView != null) && (convertView.getId() == 0x0123)) {
				convertView = null;
			}

			final ItemHolder holder;
			if (null == convertView) {
				convertView = inflater.inflate(R.layout.post_part_item, parent, false);
				holder = new ItemHolder();

				holder.icon = (ImageView) convertView.findViewById(R.id.post_part_image);
				holder.title = (TextView) convertView.findViewById(R.id.post_part_title);
				holder.price = (TextView) convertView.findViewById(R.id.post_part_price);
				holder.category = (TextView) convertView.findViewById(R.id.post_part_category);
				holder.brand = (TextView) convertView.findViewById(R.id.post_part_brand);
				holder.dateTime = (TextView) convertView.findViewById(R.id.post_part_date_time);

				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			convertView.setId(0x11 + position);
			convertView.setOnClickListener(this);

			try {
				final JSONObject obj = filterdList.get(position);

				final String icon = obj.getString("icon");
				if (icon == null || icon.length() == 0) {
					holder.icon.setImageBitmap(null);
				} else {
					imageLoader.displayImage(obj.getString("icon"), holder.icon);
				}

				holder.title.setText(obj.getString("title"));
				holder.brand.setText("Brand : " + obj.getString("brand_name"));
				holder.category.setText("Category : " + obj.getString("category_name"));
				holder.dateTime.setText(obj.getString("time"));
				holder.price.setText("Price : " + obj.getString("price") + " Baht");

			} catch (final JSONException e) {
				LogUtil.e(TAG, e.getMessage(), e);
			}
			return convertView;
		}
		@Override
		public void onClick(View v) {
			final int position = v.getId() - 0x11;
			final JSONObject obj = filterdList.get(position);

			final Intent intent = new Intent(PostPartFragment.this, AddEditFormFragment.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			intent.putExtra("detail", obj.toString());
			startActivity(intent);
		}

		@Override
		public boolean onLongClick(View v) {

			// final String[] menus = {"Delete", "Cancel"};
			// final AlertDialog.Builder builder = new
			// AlertDialog.Builder(PostPartFragment.this);
			// builder.setItems(menus, new DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(DialogInterface dialog, int which) {
			// if (which == 0) {
			//
			// } else {
			// dialog.dismiss();
			// }
			// }
			// });
			// builder.create().show();

			return false;
		}

		@Override
		public Filter getFilter() {
			final Filter filter = new Filter() {

				@Override
				protected FilterResults performFiltering(CharSequence constraint) {

					final List<JSONObject> tempList = new ArrayList<JSONObject>();

					FilterResults results = new FilterResults();

					Log.d("Filterd", "Constraint : " + constraint);

					if (constraint == null || constraint.length() == 0) {
						tempList.addAll(list);
					} else {

						constraint = constraint.toString().toLowerCase(Locale.UK);

						for (final JSONObject obj : list) {

							try {
								final String title = obj.getString("title");

								final String brandName = obj.getString("brand_name");
								final String modelName = obj.getString("model_name");

								Log.d("Filter Position", "Brand Name : " + brandName + ", with : " + constraint);

								if (title != null) {
									if (title.toLowerCase(Locale.UK).contains(constraint)) {
										tempList.add(obj);
										continue;
									}
								}

								if (brandName != null) {
									if (brandName.toLowerCase(Locale.UK).contains(constraint)) {
										tempList.add(obj);
										continue;
									}
								}

								if (modelName != null) {
									if (modelName.toLowerCase(Locale.UK).contains(constraint)) {
										tempList.add(obj);
										continue;
									}

								}

							} catch (JSONException e) {
								Log.e("Filter Exception", e.getMessage(), e);
							}
						}

					}

					results.count = tempList.size();
					results.values = tempList;

					return results;
				}

				@SuppressWarnings("unchecked")
				@Override
				protected void publishResults(CharSequence constraint, FilterResults results) {
					filterdList.clear();
					filterdList.addAll((List<JSONObject>) results.values);
					notifyDataSetChanged();
				}

			};

			return filter;
		}
	}

	private void doDelete(final String postId) {
	}

	private static class ItemHolder {
		ImageView icon;
		TextView title;
		TextView brand;
		TextView category;
		TextView dateTime;
		TextView price;
		ImageButton edit;
	}

	@Override
	public boolean onMenuClick(View v) {
		final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchField.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
		return super.onMenuClick(v);
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(searchField.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
			return true;
		}

		return false;
	}

	@Override
	public void afterTextChanged(Editable s) {
		adapter.getFilter().filter(searchField.getText().toString());
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}
}
